package com.chilly.jdkNio.action;

import io.netty.util.CharsetUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 应用实例1：使用一个Buffer完成文件读取
 * 1) 使用fileChannel 和方法 read write ，完成文件拷贝
 * 2） 拷贝一个文本文件1.txt
 * <p>
 * Created by Chilly Cui on 2021/1/9.
 */
public class NIOFileChannelOper03 {
    public static void main(String[] args) throws IOException {
        //File file = new File("c:\\env\\file01.txt");
        FileInputStream in = new FileInputStream("c:\\env\\file01.txt");
        FileChannel inChannel = in.getChannel();

        FileOutputStream out = new FileOutputStream("c:\\env\\1.txt");
        FileChannel outChannel = out.getChannel();

        //读取
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        while (true) {//循环读取
            byteBuffer.clear();//清空buffer
            int read = inChannel.read(byteBuffer);
            System.out.println("read= " + read);// 512 434 -1
            if (read == -1) { //表示读完
                break;
            }

            //转换
            byteBuffer.flip();

            //写出
            outChannel.write(byteBuffer);
        }


        in.close();
        out.close();
        in.close();
        outChannel.close();
    }
}
